<?php

namespace App\Libs;

use Cache;
use Log;
use Illuminate\Support\Facades\Redis;

/* 微信公众平台 */

class WeChatPublic
{
    //获取 SimpleXMLElement 对象
    public function getSimpleXMLElement()
    {
        //     SimpleXMLElement Object
        // (
        //     [ToUserName] => gh_6b6028abcdf8
        //     [FromUserName] => o6S8uwp__2rUmx7UlDhah0JhVzt0
        //     [CreateTime] => 1573731070
        //     [MsgType] => event
        //     [Event] => SCAN
        //     [EventKey] => 666
        //     [Ticket] => gQH48DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyNlp2YmN6RkxjSzIxV09QZE50MW0AAgQSJ81dAwSgjAAA
        // )

        // <xml><ToUserName><![CDATA[gh_6b6028abcdf8]]></ToUserName>
        // <FromUserName><![CDATA[o6S8uwp__2rUmx7UlDhah0JhVzt0]]></FromUserName>
        // <CreateTime>1573730544</CreateTime>
        // <MsgType><![CDATA[event]]></MsgType>
        // <Event><![CDATA[SCAN]]></Event>
        // <EventKey><![CDATA[666]]></EventKey>
        // <Ticket><![CDATA[gQH48DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyNlp2YmN6RkxjSzIxV09QZE50MW0AAgQSJ81dAwSgjAAA]]></Ticket>
        // </xml>
        if ($this->checkSignature()) {
            $input = file_get_contents("php://input");
            $obj = simplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA);
            return $obj;
            // $data = json_decode(json_encode($obj), true);
            // $arr = json_decode($obj, true);
            // $data = print_r($obj, true);
            // file_put_contents("weChat.txt", $obj->Event);
            // // echo $echostr;
            // echo "success";
        } else {
            return false;
        }
    }

    //临时二维码请求
    public function getQrCodeInfo($scene_str, $expire_seconds)
    {
        $access_token = $this->getAccessToken();
        $post_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$access_token}";

        $data = [
            "expire_seconds" => $expire_seconds,
            "action_name" => "QR_STR_SCENE",
            "action_info" => [
                "scene" => [
                    "scene_str" => config('constant.app_name') . '***' . $scene_str  //场景值ID（字符串形式的ID），字符串类型，长度限制为1到64
                ]
            ]
        ];

        $json_data = json_encode($data); //转化成json让微信可以接收
        $res = $this->https_request($post_url, urldecode($json_data)); //请求开始

        $arr_res = json_decode($res, true);

        if (!isset($arr_res['url'])) {
            $arr_res['url'] = "none";
            $arr_res['ticket'] = "";
        };
        return $arr_res;
    }

    //获取access_token
    public function getAccessToken()
    {
        // access_token的有效期目前为2个小时，需定时刷新，重复获取将导致上次获取的access_token失效，所以多个项目的access_token缓存要共用

        $redis = Redis::connection('public');

        $seconds = 7000; //token缓存的时间，单位 秒，微信服务器2小时过期

        $access_token = $redis->get('wechat_access_token');
        // $redis->exists('wechat_access_token') === 0
        if ($access_token === null) {
            # 缓存不存在，访问微信接口获取access_token
            $appid = config('constant.wechat_app_id');
            $secret = config('constant.wechat_app_secret');
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";

            $str_access_token = file_get_contents($url);
            $arr_access_token = json_decode($str_access_token, true);

            $access_token = $arr_access_token['access_token'];
            $redis->set('wechat_access_token', $access_token, 'EX', $seconds);
        }
        // else{
        //     # 缓存存在
        //     $access_token = $redis->get('wechat_access_token');
        // }

        return $access_token;
    }

    //curl请求函数，微信都是通过该函数请求
    private function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            //curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /* 接口配置信息验证 */
    public function interfaceCheck()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = config('constant.wechat_token');
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($this->checkSignature()) {
            $echostr = $_GET["echostr"];
            echo $echostr;
        } else {
            echo "error";
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = config('constant.wechat_token');
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    //获取设置的行业信息  http请求方式：GET
    public function getIndustry()
    {
        $access_token = $this->getAccessToken();
        $get_url = "https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token={$access_token}";
        $res = $this->https_request($get_url); //请求开始
        return $res;
    }

    //发送模板消息
    public function sendTemplateMessage($data)
    {
        $access_token = $this->getAccessToken();
        //模板消息请求URL
        $post_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";

        $json_data = json_encode($data); //转化成json数组让微信可以接收
        $res = $this->https_request($post_url, urldecode($json_data)); //请求开始

        // file_put_contents("templateMessageReturn.log", $res);
    }

}
